import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from apps.goods.models import SKU
from apps.users.models import User
import re
from django.contrib.auth import authenticate
from django_redis import get_redis_connection


# Create your views here.
class UsernameCountView(View):
    def get(self,request,username):
        # if not re.match("[a-zA-Z0-9_-]{5,20}",username):
        #     return JsonResponse({'code':200,'errmsg':'用户名不满足需求'})
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})

class PhoneNumberCountView(View):
    def get(self,request,phonenumber):
        # if not re.match("[a-zA-Z0-9_-]{5,20}",username):
        #     return JsonResponse({'code':200,'errmsg':'用户名不满足需求'})
        count = User.objects.filter(mobile=phonenumber).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})


class RegisterView(View):
    def post(self,request):
        body = json.loads(request.body)
        username = body.get('username')
        password = body.get('password')
        password2 = body.get('password2')
        mobile = body.get('mobile')
        sms_code = body.get('sms_code')
        allow = body.get('allow')
        # all里面的元素只要是False就返回False,否则返回True
        if not all([username,password,password2,mobile,allow]):
            return JsonResponse({"code":400,"errmsg":"参数不对"})
        if (not re.match('[a-zA-Z0-9_-]{5,20}', username)) or re.match("^\d+$",username):
            print(username)
            return JsonResponse({"code":400,"errmsg":"用户名不满足规则"})
        if not re.match('[a-zA-Z0-9_-]{8,20}', password):
            return JsonResponse({"code":400,"errmsg":"密码不满足规则"})
        if password2 != password:
            return JsonResponse({"code":400,"errmsg":"两次密码不相同"})
        if not re.match("1[3-9]\d{9}", mobile):
            return JsonResponse({"code":400,"errmsg":"手机号码不满足规则"})
        if not allow:
            return JsonResponse({"code":400,"errmsg":"未勾选协议"})

        # 判断短信验证码是否正确：跟图形验证码的验证一样的逻辑
        # 提取服务端存储的短信验证码：以前怎么存储，现在就怎么提取
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get(mobile)  # sms_code_server是bytes
        # 判断短信验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # 返回值user是已经登录的用户信息
        user = User.objects.create_user(username=username,password=password,mobile=mobile)
        # request.session['user_id'] = username
        # django提供了状态保持的方法
        from django.contrib.auth import login
        login(request, user)
        return JsonResponse({"code":0,"errmsg":"ok"})


#登录
"""
    
"""
class LoginView(View):
    def post(self,request):
        # 接收数据
        body = json.loads(request.body)
        username = body.get('username')
        password = body.get('password')
        remembered = body.get('remembered')
        # 验证数据
        if not all([username,password]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 用户名和手机号都可以通过修改USERNAME_FIELD进行查询
        if re.match('1[3-9]\d{9}',username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        #用户名和密码正确返回User信息,不正确返回None
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})
        #session
        from django.contrib.auth import login
        login(request, user)
        if remembered:
            # 记住登录,默认两周
            request.session.set_expiry(None)
        else:
            #不记住登录,浏览器关闭就过期
            request.session.set_expiry(0)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie("username",username,max_age=3600)
        return response

from django.contrib.auth import logout
class LogoutView(View):
    def delete(self,request):
        # 删除session
        logout(request)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        #删除cookie
        response.delete_cookie("username")
        return response

# 用户中心,必须是登录用户
from utils.views import LoginRequiredJSONMixin  #判断是否是登录用户
class CenterView(LoginRequiredJSONMixin,View):
    def get(self,request):
        # 获取界面需要的数据,进行拼接
        #request.user是已经登录的用户信息
        info_data = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        response = JsonResponse({'code': 0, 'errmsg': 'ok','info_data':info_data})

        return response

class EmailView(LoginRequiredJSONMixin,View):
    def put(self,request):
        data = json.loads(request.body)
        email = data.get('email')
        print(email)
        #验证数据
        # 校验参数
        if not email:
            return JsonResponse({'code': 400,'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,'errmsg': '参数email有误'})
        #保存数据
        user = request.user
        user.email = email
        user.save()
        # 发送激活邮件
        #subject 主题
        #html_message 发送html信息
        #from_email 发件人
        #recipient_list 收件人列表
        from apps.users.utils import generate_verify_email_url
        token = generate_verify_email_url(request.user)
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=%s'%token

        from celery_tasks.email.tasks import celery_send_email
        celery_send_email.delay(verify_url=verify_url, recipient_list=[email])

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

class EmailVerifyView(View):
    def put(self,request):
        #接收参数
        param = request.GET
        token = param.get('token')
        #验证参数
        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})

        from apps.users.utils import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code': 400, 'errmsg': '参数错误'})

        #根据用户id进行查询
        user = User.objects.get(id=user_id)
        #修改数据
        user.email_active = True
        user.save()
        #返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

from apps.users.models import Address
class CreateAddressView(LoginRequiredJSONMixin,View):
    def post(self,request):

        count = request.user.addresses.count()
        if count >= 20:
            return JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        #接收请求
        data = json.loads(request.body)
        #获取数据
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '固定电话格式有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '邮箱格式有误'})

        #数据入库
        address = Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email,

        )
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        #返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok','address': address_dict})


class AddressView(LoginRequiredJSONMixin,View):
    def get(self,request):
        addresses = Address.objects.filter(user=request.user,
                                           is_deleted=False)
        address_list = []
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok','addresses': address_list,'default_address_id':request.user.default_address_id})

class UpdateAddressView(LoginRequiredJSONMixin, View):
    def put(self,request,address_id):
        # 接收参数
        json_dict = json.loads(request.body)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号格式有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '固定电话格式有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '邮箱格式有误'})

        # 判断地址是否存在,并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})


    def delete(self,request,address_id):
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)

            # 将地址逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

            # 响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})

class DefaultAddressView(LoginRequiredJSONMixin, View):
    def put(self,request,address_id):

        try:
            # 接收参数,查询地址
            address = Address.objects.get(id=address_id)

            # 设置地址为默认地址
            request.user.default_address = address
            request.user.save()
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

            # 响应设置默认地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})

class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    def put(self,request,address_id):

        json_dict = json.loads(request.body)
        title = json_dict.get('title')

        try:
            # 查询地址
            address = Address.objects.get(id=address_id)

            # 设置新的地址标题
            address.title = title
            address.save()
        except Exception as e:

            return JsonResponse({'code': 400, 'errmsg': '设置地址标题失败'})

        # 4.响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '设置地址标题成功'})


class ChangePasswordView(LoginRequiredJSONMixin, View):
    def put(self,request,address_id):

        # 接收参数
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')

        # 校验参数
        if not all([old_password, new_password, new_password2]):
            return JsonResponse({'code': 400,'errmsg': '缺少必传参数'})

        result = request.user.check_password(old_password)
        if not result:
            return JsonResponse({'code': 400,'errmsg': '原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400,'errmsg': '两次输入密码不一致'})
        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:

            return JsonResponse({'code': 400,'errmsg': '修改密码失败'})
        # 清理状态保持信息
        logout(request)

        response = JsonResponse({'code': 0,'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response

class UserBrowseHistory(LoginRequiredJSONMixin,View):
    """用户浏览记录"""

    def post(self, request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此商品'})
        #连接redis
        redis_cli = get_redis_connection('history')
        #去重(先删除再添加)
        redis_cli.lrem('history_%s'%request.user.id,0, sku_id)
        #保存在redis
        redis_cli.lpush('history_%s'%request.user.id, sku_id)
        #只保存五条记录
        redis_cli.ltrim('history_%s'%request.user.id, 0, 4)

        return JsonResponse({'code': 0, 'errmsg': 'ok'})

        pass

    def get(self,request):
        #连接redis
        redis_cli = get_redis_connection('history')
        #通过商品id进行数据查询
        ids = redis_cli.lrange('history_%s'%request.user.id, 0, 4)
        history_list = []
        for sku_id in ids:
            sku = SKU.objects.get(id=sku_id)
            history_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })
        return JsonResponse({'code': 0, 'errmsg': 'ok',"skus":history_list})

        pass